package com.eportal.DAO;

import java.io.Serializable;
import java.sql.Connection;
import java.util.List;
import org.hibernate.*;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.eportal.ORM.MpayAccount;
import com.eportal.ORM.MpayDkAccountInfo;
import com.eportal.ORM.MpayOrg;
import com.eportal.ORM.MpayShop;
import com.eportal.ORM.MpayUser;
import com.eportal.ORM.TermReady;
import com.eportal.ORM.TermReadyView;
import com.eportal.core.Util;

/** ͳһ��ݷ��ʽӿ�ʵ�� */
public class BaseDAOImpl extends HibernateDaoSupport implements BaseDAO {

	/** ͳ��ָ��������г־û����� */

	
	public List findBySql(String sql){return null;}
	public void delete(Object object) {
		getHibernateTemplate().delete(object);
	}

	public int countAll(String clazz) {
		final String hql = "select count(*) from " + clazz + " as a";
		Long count = (Long) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Query query = session.createQuery(hql);
						query.setMaxResults(1);
						return query.uniqueResult();
					}
				});
		return count.intValue();
	}

	/** ͳ��ָ����Ĳ�ѯ��� */
	public int countQuery(String hql) {
		final String counthql = hql;
		Long count = (Long) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Query query = session.createQuery(counthql);
						query.setMaxResults(1);
						return query.uniqueResult();
					}
				});
		return count.intValue();
	}

	/** ɾ��ָ��ID�ĳ־û����� */
	public void delById(Class clazz, Serializable id) {
		getHibernateTemplate().delete(getHibernateTemplate().load(clazz, id));
	}

	/** װ��ָ��������г־û����� */
	public List listAll(String clazz) {
		return getHibernateTemplate().find(
				"from " + clazz + " as a order by a.id desc");
	}

	public void save(Object obj) {
		this.getHibernateTemplate().save(obj);
	}

	/** ��ҳװ��ָ��������г־û����� */
	public List listAll(String clazz, int pageNo, int pageSize) {
		final int pNo = pageNo;
		final int pSize = pageSize;
		final String hql = "from " + clazz + " as a order by a.id desc";
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Query query = session.createQuery(hql);
				query.setMaxResults(pSize);
				query.setFirstResult((pNo - 1) * pSize);
				List result = query.list();
				if (!Hibernate.isInitialized(result))
					Hibernate.initialize(result);
				return result;
			}
		});
		return list;
	}

	/** ����ָ��ID�ĳ־û����� */
	public Object loadById(Class clazz, Serializable id) {
		return getHibernateTemplate().get(clazz, id);
	}

	/** �������������ĳ־û����� */
	public Object loadObject(String hql) {
		final String hql1 = hql;
		Object obj = null;
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Query query = session.createQuery(hql1);
				return query.list();
			}
		});
		if (list.size() > 0)
			obj = list.get(0);
		return obj;
	}

	/** ��ѯָ��������������ĳ־û����� */
	public List query(String hql) {
		final String hql1 = hql;
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Query query = session.createQuery(hql1);
				return query.list();
			}
		});
	}

	/** ��ҳ��ѯָ��������������ĳ־û����� */
	public List query(String hql, int pageNo, int pageSize) {
		final int pNo = pageNo;
		final int pSize = pageSize;
		final String hql1 = hql;
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Query query = session.createQuery(hql1);
				query.setMaxResults(pSize);
				query.setFirstResult((pNo - 1) * pSize);
				List result = query.list();
				if (!Hibernate.isInitialized(result))
					Hibernate.initialize(result);
				return result;
			}
		});
	}

	/** ��������ָ���ĳ־û����� */
	public void saveOrUpdate(Object obj) {
		getHibernateTemplate().saveOrUpdate(obj);
	}

	/** ����������� */
	public int update(String hql) {
		final String hql1 = hql;
		return ((Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Query query = session.createQuery(hql1);
						return query.executeUpdate();
					}
				})).intValue();
	}

	/** �����ӳ���ȡ��һ��JDBC���� */
	public Connection getConnection() {
		return getHibernateTemplate().getSessionFactory().getCurrentSession()
				.connection();
	}

	public void updateDkAccount(int id) {

		Session sess = this.getHibernateTemplate().getSessionFactory()
				.openSession();
		Transaction ts = sess.beginTransaction();
		// 更新dk_account
		MpayDkAccountInfo acc = (MpayDkAccountInfo) this.getHibernateTemplate()
				.load(MpayDkAccountInfo.class, id);
		acc.setFlag("1");
		this.getHibernateTemplate().save(acc);
		List tmp = this.getHibernateTemplate().find(
				"from MpayShop where shopCode = '" + acc.getShopCode() + "' ");
		if (tmp.size() == 0) {
			MpayShop shop = new MpayShop();
			shop.setShopArea("上海");
			shop.setShopBank("天天快递");
			shop.setShopCode(acc.getShopCode());
			shop.setShopDate("-");
			shop.setShopLinkman(acc.getShopLinkman());
			if (acc.getShopName().startsWith("上海")) {
				shop.setShopName("TTSH_" + acc.getShopName());
			} else if (acc.getShopName().indexOf("_") != -1) {
				shop.setShopName(acc.getShopName());
				acc.setShopName(acc.getShopName().substring(
						acc.getShopName().indexOf("_") + 1));
			} else {
				shop.setShopName("TTKD_" + acc.getShopName());
			}
			shop.setShopPhone(acc.getShopLinkphone());
			shop.setShopType("快递");
			this.getHibernateTemplate().saveOrUpdate(shop);
			MpayShop lastshop = (MpayShop) this.getHibernateTemplate().find(
					"from MpayShop where shopCode = '" + acc.getShopCode()
							+ "' ").get(0);
			MpayUser user = new MpayUser();
			user.setIsAdmin(1);
			user.setIsAll(0);
			user.setMpayCreate(Util.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
			user.setMpayFlag("0");
			if(acc.getShopCode().startsWith("P"))
				user.setMpayGroupid("38");
			else
				user.setMpayGroupid("17");
			user.setMpayLogCount(0);
			user.setMpayLogip("-");
			user.setMpayLogtime("-");
			user.setMpayTermid(acc.getShopLinkphone());
			user.setMpayUserid(acc.getShopCode());
			user.setMpayUsername(acc.getShopName());
			user.setShopId(lastshop.getId() + "");
			user.setMpayPassword(acc.getBankAccount().substring(
					acc.getBankAccount().length() - 6));
			this.getHibernateTemplate().save(user);
		}
		MpayShop lastshop = (MpayShop) this.getHibernateTemplate().find(
				"from MpayShop where shopCode = '" + acc.getShopCode() + "' ")
				.get(0);
		MpayUser u = (MpayUser) this.getHibernateTemplate().find(
				"from MpayUser where shop_id = '" + lastshop.getId() + "' ")
				.get(0);
		MpayAccount account = new MpayAccount();
		account.setRcvBank(acc.getBankName());
		account.setRcvBankjx("-");
		account.setRcvFlag("1");
		account.setRcvBankname(acc.getBankName());
		account.setRcvBankno("99999999");
		account.setRcvMobile(acc.getShopLinkphone());
		account.setRcvCdno(acc.getBankAccount());
		account.setRcvName(acc.getAccountName());
		account.setRcvDate(Util.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		account.setRcvTerm(u.getId() + "");
		account.setRcvType("3");
		this.getHibernateTemplate().saveOrUpdate(account);
		try {
			ts.commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ts.rollback();
		}
		sess.close();
	}

	public void saveUser(TermReadyView ready) {
		MpayShop shop = new MpayShop();
		shop.setShopArea("-");
		shop.setShopBank(ready.getBank());
		shop.setShopCode("-");
		shop.setShopDate(Util.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		shop.setShopLinkman(ready.getLinkman());
		shop.setShopPhone(ready.getLinkmanphone());
		shop.setShopType("-");
		shop.setShopName(ready.getUsername());
		this.getHibernateTemplate().save(shop);
		MpayOrg org = new MpayOrg();
		MpayShop lastshop = (MpayShop) this.getHibernateTemplate().find(
				"from MpayShop order by id desc").get(0);
		int shopid = lastshop.getId();
		org.setShopId(shopid + "");
		org.setTermCardno(ready.getIncdno());
		org.setTermCreateDt(ready.getAppdt());
		if (ready.getTermid().startsWith("POS")) {
			org.setTermid(ready.getTermid().substring(3));
		} else {
			org.setTermid(ready.getTermid());
		}
		org.setTermLinkaddress(ready.getAddress());
		org.setTermLinkname(ready.getLinkman());
		org.setTermLinkphone(ready.getLinkmanphone());
		org.setTermName(ready.getUsername());
		org.setTermNick("-");
		org.setTermPsam("-");
		org.setTermUpdateDt("-");
		org.setUserid("-");
		this.getHibernateTemplate().save(org);
		MpayUser user = new MpayUser();
		if (ready.getTable() != null && !ready.getTable().equals(""))
			user.setIsAdmin(Integer.valueOf(ready.getTable()));
		else
			user.setIsAdmin(1);
		user.setIsAll(0);
		user.setMpayCreate(Util.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		user.setMpayFlag("0");
		if (ready.getTermid().startsWith("C")
				&& ready.getBank().equals("RCARD")) {
			user.setMpayGroupid("30");
		} else if (ready.getBank().indexOf("MKL") != -1) {
			user.setMpayGroupid("34");
		} else {
			user.setMpayGroupid("29");
		}
		user.setMpayLogCount(0);
		user.setMpayLogip("-");
		user.setMpayLogtime("-");
		if (ready.getTermid().startsWith("C")) {
			user.setMpayTermid(ready.getTermid());
			user.setMpayUserid(ready.getTermid().substring(1));
		} else {
			user.setMpayTermid(ready.getTermid());
			user.setMpayUserid(ready.getTermid());
		}
		user.setMpayUsername(ready.getUsername());
		user.setShopId(shopid + "");
		user.setMpayPassword(ready.getIncdno().substring(
				ready.getIncdno().length() - 6));
		this.getHibernateTemplate().save(user);
		// TermReady t =
		// (TermReady)this.loadObject(" from TermReady where termid = '"+ready.getTermid()+"'");
		// t.setFlag("1");
		// this.getHibernateTemplate().update(t);
	}

	public long sum(String sql) {
		List li = getSession().createQuery(sql).list();
		if (li == null || li.isEmpty()) {
			return (long) 0;
		} else {
			if (li.get(0) == null) {
				return (long) 0;
			}
			return Long.valueOf((li.get(0)+"").substring(0,(li.get(0)+"").indexOf(".")));
		}
	}
}